#include "AddDevice.h"
#include "db/DBManager.h"

#include <QDebug>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QJsonObject>
#include <QJsonArray>
#include <QSqlError>


/*


@app.route('/addDevice')
def addDevice():
    device_name = request.args.get("device_name")
    openid = request.args.get("openid")
    if openid=='' or device_name=='':
        return json.dumps({"result":"error"})

    sql = "insert into manager_device(szOpenid, szDeviceName) values('%s', '%s')"
    print('sql: ', sql % (openid,device_name))

    db_core_config.ping(reconnect=True)
    db_cursor.execute(sql % (openid,device_name))
    db_core_config.commit()

    return json.dumps({"result":"ok"})

*/

void AddDevice::handleSession()
{
    qDebug() << "AddDevice requestUrlQuery: " << m_session->requestUrlQuery();

    QMap<QString, QString> mapQuery = m_session->requestUrlQuery();

    QString strOpenId = mapQuery.value("openid");
    QString strDeviceName = mapQuery.value("device_name");

    if (strOpenId.simplified().isEmpty() || strDeviceName.simplified().isEmpty())
    {
        QJsonObject obj;
        obj.insert("result", "error:info empty");
        m_session->replyJsonObject(obj);
        return;
    }

    QSqlDatabase db = DBManager::database("core_config");

    QString strSql = QString("insert into manager_device(szOpenid, szDeviceName) values('%1', '%2')").arg(strOpenId).arg(strDeviceName);

    QSqlQuery query(db);

    if(!query.exec(strSql))
    {
        qDebug()<<"exec insert manager_device error, "<<query.lastError().text();
        QJsonObject obj;
        obj.insert("result", "error:insert manager_device");
        m_session->replyJsonObject(obj);
        return;
    }

    QJsonObject obj;
    obj.insert("result", "ok");
    m_session->replyJsonObject(obj);
}
